package ink.sunflowerk.dao.impl;

import ink.sunflowerk.dao.TeacherDao;
import ink.sunflowerk.pojo.Teacher;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zhaokuii11@163.com
 * @create 2021-12-09 9:31
 * @Description
 */
@Repository//用在持久陈的
//@EnableTransactionManagement
@Transactional
public class TeacherDaoImpl implements TeacherDao {
    @Autowired
    SessionFactory sessionFactory;

    @Override
    public Teacher getTeacher(String username, String password) {
        Session session = sessionFactory.openSession();
        String hql = "from Teacher t where  t.teacherName = ?1 and t.teacherPwd = ?2";
        Query query = session.createQuery(hql);
        query.setParameter(1, username);
        query.setParameter(2, password);

        List<Teacher> list = query.list();
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void insertTeacher(Teacher teacher) {
        Session session = sessionFactory.getCurrentSession();
        session.save(teacher);
    }

    @Override
    public Integer deleteTeacherById(Integer id) {
//        Session session = sessionFactory.openSession();
        Session session = sessionFactory.getCurrentSession();
        String sql = "delete from tab_teacher where t_id = ?";
        NativeQuery nativeQuery = session.createSQLQuery(sql);
        nativeQuery.setParameter(1, id);
        return nativeQuery.executeUpdate();
    }

    @Override
    public Teacher getTeacher(String phone) {
        Session session = sessionFactory.openSession();
        String hql = "from Teacher t where  t.tPhone =?1";
        Query query = session.createQuery(hql);
        query.setParameter(1, phone);
        List<Teacher> list = query.list();
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

}
